<?php


namespace app\admin\library\builder;


class KeyManager
{
    private $keys = [];

    private static $obj;

    public static function factory()
    {
        if (!self::$obj) {
            self::$obj = new static();
        }
        return self::$obj;
    }

    public function __construct()
    {
    }


    /**
     * 申请组件key
     * @param string $name
     * @return string|bool
     */
    public function apply($name)
    {
        for ($i = 0; $i < 30; $i++) {
            $id = $this->getKeySuffix();
            if (empty($this->keys[$id])) {
                $this->keys[] = $id;
                return $name . '_' . $id;
            }
        }
        return false;
    }


    private function getKeySuffix()
    {
        $str = str_pad(mt_rand(0, 9999999), 7, '0', STR_PAD_LEFT);

        return $str;
    }
}
